//计算字符串宽度
String.prototype.pxWidth = function (font) {
  // re-use canvas object for better performance
  var canvas = String.prototype.pxWidth.canvas || (String.prototype.pxWidth.canvas = document.createElement("canvas")),
    context = canvas.getContext("2d");
  font && (context.font = font);
  var metrics = context.measureText(this);
  return metrics.width;
}

const app = new Vue({
  el: '#app',
  data: {
    flagRight: false,
    isShow1: true,
    isShow2: true,
    radius: '',
    from: { name: '中文(简体)', code: 'zh' },
    to: { name: '英语', code: 'en' },
    fromCon: '',
    toCon: '',
    tofontsize: '26px',
    fromfontsize: '26px',
    langdataList: [{ name: '中文(简体)', code: 'zh' }, { name: '英语', code: 'en' }, { name: '粤语', code: 'yue' }, { name: '文言文', code: 'wyw' },
    { name: '日语', code: 'jp' }, { name: '韩语', code: 'kor' }, { name: '法语', code: 'fra' }, { name: '西班牙语', code: 'spa' },
    { name: '泰语', code: 'th' }, { name: '阿拉伯语', code: 'ara' }, { name: '俄语', code: 'ru' }, { name: '葡萄牙语', code: 'pt' },
    { name: '德语', code: 'de' }, { name: '意大利语', code: 'it' }, { name: '希腊语', code: 'el' }, { name: '荷兰语', code: 'nl' },
    { name: '波兰语', code: 'pl' }, { name: '保加利亚语', code: 'bul' }, { name: '爱沙尼亚语', code: 'est' }, { name: '丹麦语', code: 'dan' },
    { name: '芬兰语', code: 'fin' }, { name: '捷克语', code: 'cs' }, { name: '罗马尼亚语', code: 'rom' }, { name: '斯洛文尼亚语', code: 'slo' },
    { name: '瑞典语', code: 'swe' }, { name: '匈牙利语', code: 'hu' }, { name: '中文(繁体)', code: 'cht' }, { name: '越南语', code: 'vie' }
    ],
    commonfromLangList: [{ name: '自动检测', code: 'auto' }, { name: '中文(简体)', code: 'zh' }],
    commontoLangList: [{ name: '英语', code: 'en' }],
    showLanglist: '',
    isSelected: '',
    unSelected: '',
    isSelectedcommon: '',
    unSelectedcommon: ''
  },
  methods: {
    fromLang(e) {
      this.flagRight = false
      this.isShow1 = !this.isShow1
      this.isShow2 = true
      this.radius = '0 12px 12px 12px'
      e.target.style.borderRadius = this.isShow1 === false ? '12px 12px 12px 12px' : '12px 12px 12px 0'
      this.showLanglist = this.commonfromLangList
      this.isSelected = this.langdataList.findIndex(item => item.name === this.from.name)//标记列表项中选中项
      this.unSelected = this.langdataList.findIndex(item => item.name === this.to.name)//标记列表项中不可选项
      this.isSelectedcommon = this.showLanglist.findIndex(item => item.name === this.from.name)//标记常用列表项中选中项
      this.unSelectedcommon = this.showLanglist.findIndex(item => item.name === this.to.name)//标记常用列表项中不可选项

    },
    toLang(e) {
      this.flagRight = false
      this.isShow2 = !this.isShow2
      this.isShow1 = true
      this.radius = '12px 12px 12px 12px'
      e.target.style.borderRadius = this.isShow2 === true ? '12px 12px 12px 12px' : '12px 12px 0 0'
      this.isSelected = this.langdataList.findIndex(item => item.name === this.to.name)//标记列表项中选中项
      this.unSelected = this.langdataList.findIndex(item => item.name === this.from.name)//标记列表项中不可选项
      this.showLanglist = this.commontoLangList
      this.isSelectedcommon = this.showLanglist.findIndex(item => item.name === this.to.name)//标记常用列表项中选中项
      this.unSelectedcommon = this.showLanglist.findIndex(item => item.name === this.from.name)//标记常用列表项中不可选项

    },
    areaSelect() {
      this.flagRight = !this.flagRight
      this.radius = '0 12px 12px 12px'
      this.isShow1 = this.isShow2 = true
    },
    mutu(e) {
      /* console.log(e.target.style.transform) *///第一次触发点击时，js无法直接获取dom元素的样式属性值，刷新页面时css先于js加载出来，所以需要同时在css中添加dom元素的属性和在HTML中找到对应dom标签绑定style添加属性值。
      e.target.style.transform = e.target.style.transform === 'scaleX(-1)' ? 'scaleX(1)' : 'scaleX(-1)'
      let temp = 0
      temp = this.to
      this.to = this.from
      this.from = temp
      this.isShow1 = this.isShow2 = true
    },
    fromContent(e) {
      this.fromCon.pxWidth('26px') > 215 ? this.fromfontsize = "16px" : this.fromfontsize = "26px"
      this.toCon.pxWidth('26px') > 200 ? this.tofontsize = "16px" : this.tofontsize = "26px"
    },
    select(e) {
      let select = this.langdataList[e.target.dataset.index].name
      let index = this.showLanglist.findIndex(item => item.name === select)
      //标记选中语言
      console.log('测试')
      if (this.isShow2) {
        if (select === this.from.name || select === this.to.name) {
          this.isShow1 = false
          this.isShow2 = true
        } else {
          index !== -1 ? this.showLanglist.splice(index, 1) ://去除常用语言选项中的重复项
            console.log('')
          if (this.commonfromLangList.length > 3) {
            this.commonfromLangList.splice(1, 1)
          }
          this.from = this.langdataList[e.target.dataset.index]
          this.commonfromLangList.push(this.from)
          this.isShow1 = this.isShow2 = true
        }
      } else if (this.isShow1) {
        if (select === this.to.name || select === this.from.name) {
          this.isShow2 = false
          this.isShow1 = true
        } else {
          index !== -1 ? this.showLanglist.splice(index, 1) ://去除常用语言选项中的重复项
            console.log('')
          if (this.commontoLangList.length > 2) {
            this.commontoLangList.splice(0, 1)
          }
          this.to = this.langdataList[e.target.dataset.index]
          this.commontoLangList.push(this.to)
          this.isShow1 = this.isShow2 = true
        }
      }
    },
    selectCommon(e) {
      let index = e.target.dataset.index
      let select = this.showLanglist[index].name
      console.log(index)
      if (this.isShow2) {
        if (select === this.to.name || select === this.from.name) {//点击已选语言项弹窗默认无法关闭
          this.isShow2 = true
          this.isShow1 = false
        }
        else if (e.target.dataset.index < this.showLanglist.length - 1 /* && e.target.dataset.index > 0 */) {//标记常用语言项的选中语言并移到最后面
          this.from = this.commonfromLangList[index]
          this.commonfromLangList.push(this.commonfromLangList[index])
          this.commonfromLangList.splice(index, 1)
          this.isShow1 = this.isShow2 = true
        }
      } else if (this.isShow1) {
        if (select === this.to.name || select === this.from.name) {//点击已选语言项弹窗默认无法关闭
          this.isShow2 = false
          this.isShow1 = true
        } else if (e.target.dataset.index < this.showLanglist.length - 1) {//标记常用语言项的选中语言并移到最后面
          this.to = this.commontoLangList[index]
          this.commontoLangList.push(this.commontoLangList[index])
          this.commontoLangList.splice(index, 1)
          this.isShow1 = this.isShow2 = true
        }
      }


    }
  },
  computed: {//判断左右弹窗是否弹出
    show1: {
      get() {
        if (!this.isShow1 || !this.isShow2) {
          return 'block'
        } else {
          return 'none'
        }
      },
      set() { }
    },
    show2() {
      return this.flagRight === true ? 'block' : 'none'
    }

  },
  watch: {
    fromCon(newVal) {
      let result = {//预先声明定义result对象,因为函数尾部定义了"this.toCon = result['trans_result'][0].dst",避免输入框为空传出的result值也为空，无法找到result['trans_result'][0]中的dist属性
        trans_result: [{ dst: '' }]
      }
      //防抖实现频繁输入减少Ajax请求次数
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (newVal == '') {
          this.toCon = ''
          return
        }
        /*  console.log(newVal, this.from.code, this.to.code) */
        let appid = '20201116000617805';
        let key = 'YQlzkV9aoQA1zxRbAEsV';
        let salt = (new Date).getTime();
        let query = newVal;
        // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
        let from = this.from.code;
        let to = this.to.code;
        let str1 = appid + query + salt + key;
        let sign = MD5(str1);
        result = await $.ajax({
          url: 'http://api.fanyi.baidu.com/api/trans/vip/translate',
          type: 'get',
          dataType: 'jsonp',
          data: {
            q: query,
            appid: appid,
            salt: salt,
            from: from,
            to: to,
            sign: sign
          },
          success: function (data) {
            /*  console.log(data) */
            return data
          }/* ,
          error: function (xhr, textstatus, errorThrow) {
            console.log('请求失败' + xhr.status)
          } */
        })
        if (newVal === '') {
          this.toCon = ''
          return
        } else {
          console.log(result)
          this.toCon = result['trans_result'][0].dst//传出的result['trans_result'][0].dst为空，可能是错误码58000 客户端IP非法 检查个人资料里填写的IP地址是否正确，可前往开发者信息-基本信息修改
        }
      }, 1000)
    }
  }
})
